<template>
    <div id="avatar">
        <div style="display: flex;flex-direction: column;align-items: center;">
            <span style="color: blue;">点击头像上传更换&nbsp;</span>
            <el-upload action="api/user/updatePic" class="avatar-uploader" :auto-upload="false" list-type="picture"
                :show-file-list="false" :limit="1" :on-change="onChangeFile">
                <el-image v-if="!(data.imgUrl)" style="width: auto;" :src="pic(store.state.user.img)"  />
                <el-image v-if="data.imgUrl" style="width:auto;" :src="data.imgUrl" fit="contain" />
            </el-upload>
        </div>
        <el-button type="success" size="default" @click="save">确认更新头像</el-button>
    </div>
</template>

<script setup> 
import { reactive } from 'vue';
import api from '../../api';
import pic from '../../api/pic';
import store from '../../store/index.js';
import { ElMessage } from 'element-plus';

const data = reactive({
	imgUrl: '', // 用于存储新选择的图片的临时 URL
	formData: new FormData() // 用于存储上传的文件数据
})

// 处理文件选择事件
const onChangeFile = (file, fileList) => {
	console.log("onChangeFile....")
	console.log(fileList)    //打印出数组
	if (fileList.length > 0) {
	    console.dir(fileList[0]);
	    // fileList[0].raw;  就是文件内容
	    data.imgUrl = URL.createObjectURL(fileList[0].raw);
	    data.formData.append('mypic', fileList[0].raw);
	}
}

const save = () => {
	console.dir(data.formData)
	api.postf("/api/user/updatePic",data.formData).then((resp)=>{
	    store.state.user.img = resp.data.data
	    if(resp.data.code == 200){
	        ElMessage.success(resp.data.msg)
	    }
	})
}
</script>

<style lang="less">
#avatar {
    height: 100%;
    display: flex;
    flex-direction: column;
    // justify-content: space-around;
    align-items: center;
    text-align: center;

    // 使用深度选择器修改 el-upload 的样式

    .avatar-uploader {
        margin-top: 20px;
        margin-bottom: 20px;
        // 设置宽度
        width: 30%;
        height: auto;
        // 可以根据需要添加其他样式，例如设置内边距、背景颜色等
        padding: 10px;
        background-color: #f5f5f5;
    }

  .el-upload.el-upload--picture{
    display: flex;
    flex-direction: column;
  }

}
</style>